package com.yulang.security.core.provider;

import com.yulang.security.core.token.MobileAuthenticationToken;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * 手机号码认证的提供者
 */
public class MobileAuthenticationProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    /**
     *认证处理，通过手机号码查询信息，通过userDetailsService实现
     * @param authentication
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        MobileAuthenticationToken authentication1 = (MobileAuthenticationToken) authentication;
        String mobile = (String)authentication1.getPrincipal();
        UserDetails userDetails = userDetailsService.loadUserByUsername(mobile);
        if(userDetails==null){
            throw new AuthenticationServiceException("手机号未注册！");
        }
        //封装到
        MobileAuthenticationToken token = new MobileAuthenticationToken(userDetails,userDetails.getAuthorities());
        token.setDetails(authentication1.getDetails());
        return token;
    }

    /**
     * 通过这个方法选择对应的provider如果返回true
     * @param authentication
     * @return
     */
    @Override
    public boolean supports(Class<?> authentication) {
        return MobileAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
